package csc.fresher.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.fresher.dao.UserDAOImpl;
import csc.fresher.domain.User;


/**
 * Servlet implementation class DownloadFileServlet
 */
public class DownloadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		UserDAOImpl dao = new UserDAOImpl();
		User user = dao.getUser(username);
		String pathFileDownload = request.getParameter("filename");
		File fileDownload = new File(pathFileDownload);
		FileInputStream is = new FileInputStream(fileDownload);
		
		String mimeType = getServletContext().getMimeType(pathFileDownload);
		if (mimeType == null) {
			// set binary type
			mimeType = "application/octet-stream";
		}
		// edit respone
		response.setContentType(mimeType);
		response.setContentLength((int) fileDownload.length());
		// force download
		String headerKey = "Content-Disposition";
		String headerValue = String.format("attachment; filename=\"%s\"", fileDownload.getName());
		response.setHeader(headerKey, headerValue);
		
		OutputStream out = response.getOutputStream();
		byte[] buffer = new byte[4096];
		int bytesRead = -1;
		while ((bytesRead = is.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
		}
		is.close();
		out.close();
		user.setDownloadDate(new Date());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
